package cgroup

import (
	"errors"
	"fmt"
	"os"
	"path"
	"strconv"
)

// 设置对应的限制值
func SetLimit(cgroupPath string, option string, value string) error {
	if cgroupPath == "" {
		return errors.New("控制组目录为空")
	} else {
		fileInfo, err := os.Stat(cgroupPath)
		if err != nil || !fileInfo.IsDir() {
			return errors.New("控制组目录异常")
		}
	}
	if option == "" {
		return errors.New("控制组文件名为空")
	}
	if value == "" {
		return errors.New("限制值为空")
	}

	optionFile := path.Join(cgroupPath, option)
	if err := os.WriteFile(optionFile, []byte(value), 0644); err != nil {
		return fmt.Errorf("set cgroup memory fail %v", err)
	}
	return nil
}

// 将进程ID添加到tasks文件中
func AppendPid(cgroupPath string, pid int) error {
	if cgroupPath == "" {
		return errors.New("控制组目录为空")
	} else {
		fileInfo, err := os.Stat(cgroupPath)
		if err != nil || !fileInfo.IsDir() {
			return errors.New("控制组目录异常")
		}
	}

	taskPath := path.Join(cgroupPath, "tasks")
	if err := os.WriteFile(taskPath, []byte(strconv.Itoa(pid)), 0644); err != nil {
		return fmt.Errorf("set cgroup proc tasks fail %v", err)
	}
	return nil
}
